package com.wechat.config;

import com.wechat.annotation.Auth;
import com.wechat.utils.CookieUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created by ycx on 2018/4/19.
 */
public class LoginInterceptor extends HandlerInterceptorAdapter {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("preHandle");
        // 判定此 Class 对象所表示的类或接口与指定的 Class 参数所表示的类或接口是否相同，或是否是其超类或超接口
        if (!handler.getClass().isAssignableFrom(HandlerMethod.class)) {
            System.out.println("cat cast handler to HandlerMethod.class");
            return true;
        }
        // 获取注解，如果不存在这个注解就放行
        Auth auth = ((HandlerMethod) handler).getMethod().getAnnotation(Auth.class);
        if (auth == null) {
            System.out.println("cant find @Auth in this uri:" + request.getRequestURI());
            return true;
        }
        // 从参数中取出用户身份并验证
        String admin = auth.user();
        Object sessionToken = request.getSession().getAttribute("sessionToken");
        Cookie cookieToken = CookieUtils.getCookie(request, "cookieToken");

        if (cookieToken != null && sessionToken != null && sessionToken.toString().equals(cookieToken.getValue())) {
            if (!"admin".equals(admin)) {
                System.out.println("没有权限");
                response.setStatus(600);
                return false;
            }
        } else {
            System.out.println("请登录");
            response.setStatus(401);
            return false;
        }
        return true;
    }

}
